<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<h1 id="isConnection"></h1>
<input type="text" id="msgInput">
<button id="btn_send">发送信息</button>
<ul id="msgList">

</ul>
<script>
  let wsClient = new WebSocket('ws://localhost:3005');

  wsClient.onopen = function () {
    // console.log('已连接');
    isConnection.innerText = "已连接"
  };

  btn_send.onclick = function () {
    let value = msgInput.value.trim();
    if (!value) {
      alert('请输入内容');
      return
    }

    wsClient.send(JSON.stringify({
      code: 1,
      msg: value
    }))
  };

  wsClient.onmessage = function (msg) {
    let {data} = msg;
    data = JSON.parse(data);
    let oLi = document.createElement('li');
    oLi.innerText = data.msg;
    msgList.appendChild(oLi);
  };


  wsClient.onclose = function () {
    // console.log('断开连接');
    isConnection.innerText = "断开连接"

  };
</script>
</body>
</html>
